﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using MyGIS.Classes;
using MyGIS.Forms;
using ESRI.ArcGIS.esriSystem;
using static System.Windows.Forms.Cursor;
using static System.Windows.Forms.Cursors;

namespace MyGIS
{
    public partial class Form1 : Form
    {


        private Pan mPan;
        private ZoomOut mZoomOut;
        private FixedZoomIn mFixedZoomIn;
        private FixedZoomOut mFixedZoomOut;
        private string mTool;//
        private ZoomIn mZoomIn;
        //空间查询的查询方式
        private int mQueryMode;
        //图层索引
        private int mLayerIndex;
        private System.Timers.Timer autoUpdateTimer;
        private bool isAutoUpdating = false;
        public Form1()
        {
            InitializeComponent();
            mPan = new Pan();
            mZoomIn = new ZoomIn();
            mZoomOut = new ZoomOut();
            mFixedZoomIn = new FixedZoomIn();
            mFixedZoomOut = new FixedZoomOut();

        }
        //
        public void UpdateDataGridView(DataTable data)
        {
            this.dataGridView1.DataSource = data;
            this.dataGridView1.Refresh();
        }
        //


        private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {

        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripContainer1_ContentPanel_Load(object sender, EventArgs e)
        {

        }

        private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void menuFileOpen_Click(object sender, EventArgs e)
        {
            //文件路径名称,包含文件名称和路径名称
            string strName = null;

            //定义OpenFileDialog，获取并打开地图文档
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开MXD";
            openFileDialog.Filter = "MXD文件（*.mxd）|*.mxd";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                strName = openFileDialog.FileName;
                if (strName != "")
                {
                    this.axMapControl1.LoadMxFile(strName);
                }
            }
            //地图文档全图显示
            this.axMapControl1.Extent = this.axMapControl1.FullExtent;
        }

        private void 添加数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ControlsAddDataCommandClass();
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
        }

        private void menuExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void menuFullExtent_Click(object sender, EventArgs e)
        {
            //初始化FullExtent对象
            FullExtent fullExtent = new FullExtent();
            //FullExtent对象与MapControl关联
            fullExtent.OnCreate(this.axMapControl1.Object);
            fullExtent.OnClick();
        }

        private void menuZoomIn_Click(object sender, EventArgs e)
        {
            toolZoomIn_Click(sender, e);
        }
        private void menuZoomOut_Click(object sender, EventArgs e)
        {
            toolZoomOut_Click(sender, e);
        }
        private void menuFixedZoomIn_Click(object sender, EventArgs e)
        {
            toolFixedZoomIn_Click(sender, e);
        }

        private void menuFixedZoomOut_Click(object sender, EventArgs e)
        {
            toolFixedZoomOut_Click(sender, e);
        }
        private void menuPan_Click(object sender, EventArgs e)
        {
            //初始化Pan对象
            mPan = new Pan();
            //Pan对象与MapControl关联
            mPan.OnCreate(this.axMapControl1.Object);
            //设置鼠标形状
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPan;
            //标记操作为“Pan”
            this.mTool = "Pan";
        }

        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {

        }

        private void axMapControl1_OnMouseDown_1(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            this.axMapControl1.Map.ClearSelection();
            //获取当前视图
            IActiveView pActiveView = this.axMapControl1.ActiveView;
            //获取鼠标点
            IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    this.mZoomOut.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "Pan":
                    //设置鼠标形状
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPanning;
                    this.mPan.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "SpaceQuery":
                    IGeometry pGeometry = null;
                    if (this.mQueryMode == 0)//矩形查询
                    {
                        pGeometry = this.axMapControl1.TrackRectangle();
                    }
                    else if (this.mQueryMode == 1)//线查询
                    {
                        pGeometry = this.axMapControl1.TrackLine();
                    }
                    else if (this.mQueryMode == 2)//点查询
                    {
                        ITopologicalOperator pTopo;
                        IGeometry pBuffer;
                        pGeometry = pPoint;
                        pTopo = pGeometry as ITopologicalOperator;
                        //根据点位创建缓冲区，缓冲半径为0.1，可修改
                        pBuffer = pTopo.Buffer(0.1);
                        pGeometry = pBuffer.Envelope;
                    }
                    else if (this.mQueryMode == 3)//圆查询
                    {
                        pGeometry = this.axMapControl1.TrackCircle();
                    }
                    IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(this.mLayerIndex) as IFeatureLayer;
                    DataTable pDataTable = this.LoadQueryResult(this.axMapControl1, pFeatureLayer, pGeometry);
                    this.dataGridView1.DataSource = pDataTable.DefaultView;

                    this.dataGridView1.Refresh();
                    break;
                default:
                    break;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    // 确保只传递鼠标移动事件给当前活动工具
                    if (this.axMapControl1.CurrentTool is ZoomOut)
                    {
                        this.mZoomOut.OnMouseMove(e.button, e.shift, e.x, e.y);
                    }
                    break;
                case "Pan":
                    this.mPan.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                default:
                    break;
            }
            // 显示当前比例尺
            this.StatusScale.Text = " 比例尺 1:"+((long)this.axMapControl1.MapScale).ToString();
            //// 显示当前坐标
            this.StatusCoordinate.Text = " 当前坐标 X = " + e.mapX.ToString() +  " Y = " +  e.mapY.ToString()  + " " +  this.axMapControl1.MapUnits;
            //this.statueCoordinate.Text = $" 当前坐标 X = {e.mapX} Y = {e.mapY} {this.axMapControl1.MapUnits}";

        }


        private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    this.mZoomOut.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "Pan":
                    this.mPan.OnMouseUp(e.button, e.shift, e.x, e.y);
                    //设置鼠标形状
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPan;
                    break;
                default:
                    break;
            }
        }

        private void menuAttributeQuery_Click(object sender, EventArgs e)
        {
            ////初始化属性查询窗体
            //AttributeQueryForm attributeQueryForm = new AttributeQueryForm(this.axMapControl1);
            //attributeQueryForm.Show();
            //初始化属性查询窗体
           using (AttributeQueryForm attributeQueryForm = new AttributeQueryForm(this.axMapControl1))
                {
                    attributeQueryForm.Owner = this;
                    attributeQueryForm.ShowDialog();
                }
        }
        private DataTable LoadQueryResult(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry)
        {
            IFeatureClass pFeatureClass = featureLayer.FeatureClass;

            //根据图层属性字段初始化DataTable
            IFields pFields = pFeatureClass.Fields;
            DataTable pDataTable = new DataTable();
            for (int i = 0; i < pFields.FieldCount; i++)//i->i++
            {
                string strFldName;
                strFldName = pFields.get_Field(i).AliasName;
                pDataTable.Columns.Add(strFldName);
            }

            //空间过滤器
            ISpatialFilter pSpatialFilter = new SpatialFilter();
            pSpatialFilter.Geometry = geometry;

            //根据图层类型选择缓冲方式
            switch (pFeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
            }
            //定义空间过滤器的空间字段
            pSpatialFilter.GeometryField = pFeatureClass.ShapeFieldName;

            IQueryFilter pQueryFilter;
            IFeatureCursor pFeatureCursor;
            IFeature pFeature;
            //利用要素过滤器查询要素
            pQueryFilter = pSpatialFilter as IQueryFilter;
            pFeatureCursor = featureLayer.Search(pQueryFilter, true);
            pFeature = pFeatureCursor.NextFeature();

            while (pFeature != null)
            {
                string strFldValue = null;
                DataRow dr = pDataTable.NewRow();
                //遍历图层属性表字段值，并加入pDataTable
                for (int i = 0; i < pFields.FieldCount; i++)//i->i++
                {
                    string strFldName = pFields.get_Field(i).Name;
                    if (strFldName == "Shape")
                    {
                        strFldValue = Convert.ToString(pFeature.Shape.GeometryType);
                    }
                    else
                        strFldValue = Convert.ToString(pFeature.get_Value(i));
                    dr[i] = strFldValue;
                }
                pDataTable.Rows.Add(dr);
                //高亮选择要素
                mapControl.Map.SelectFeature((ILayer)featureLayer, pFeature);
                mapControl.ActiveView.Refresh();
                pFeature = pFeatureCursor.NextFeature();
            }
            return pDataTable;
        }

        private void menuSpatialQuery_Click(object sender, EventArgs e)
        {
            //初始化空间查询窗体
            SpatialQueryForm spatialQueryForm = new SpatialQueryForm(this.axMapControl1);
            if (spatialQueryForm.ShowDialog() == DialogResult.OK)
            {
                //标记为“空间查询”
                this.mTool = "SpaceQuery";
                //获取查询方式和图层
                this.mQueryMode = spatialQueryForm.mQueryMode;
                this.mLayerIndex = spatialQueryForm.mLayerIndex;
                //定义鼠标形状
                this.axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerCrosshair;
            }
        }

        private void toolFullExtent_Click(object sender, EventArgs e)
        {
            //初始化FullExtent对象
            ICommand cmd = new ControlsMapFullExtentCommandClass();
            //FullExtent与MapControl的关联
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
        }

        private void toolPan_Click(object sender, EventArgs e)
        {
            //初始化Pan对象
            ITool tool = new ControlsMapPanToolClass();
            //查询接口，初试化Command类型
            ICommand cmd = tool as ICommand;
            //Command与MapControl的关联
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
            //当前MapControl的工具设为Pan
            this.axMapControl1.CurrentTool = tool;
        }
      
        private void UpdateToolbarIcons()
        {
            
            toolZoomIn.Checked = (mTool == "ZoomIn");
            toolZoomOut.Checked = (mTool == "ZoomOut");
            toolFixedZoomIn.Checked = (mTool == "FixedZoomIn");
            toolFixedZoomOut.Checked = (mTool == "FixedZoomOut");

        }
        private void toolZoomIn_Click(object sender, EventArgs e)
        {
            
            mZoomIn = new ZoomIn();
            mZoomIn.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = mZoomIn as ITool;
            this.mTool = "ZoomIn";
            UpdateToolbarIcons();
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }

        private void toolZoomOut_Click(object sender, EventArgs e)
        {
          
            mZoomOut = new ZoomOut();
            mZoomOut.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = mZoomOut as ITool;
            this.mTool = "ZoomOut";
            UpdateToolbarIcons();
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }
        private void toolFixedZoomIn_Click(object sender, EventArgs e)
        {
            mFixedZoomIn = new FixedZoomIn();
            mFixedZoomIn.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = null; // 固定缩放工具不需要设置CurrentTool
            mFixedZoomIn.OnClick();
            this.mTool = "FixedZoomIn";
            UpdateToolbarIcons();


        }

        private void toolFixedZoomOut_Click(object sender, EventArgs e)
        {
            mFixedZoomOut = new FixedZoomOut();
            mFixedZoomOut.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = null; // 固定缩放工具不需要设置CurrentTool
            mFixedZoomOut.OnClick();
            this.mTool = "FixedZoomOut";
            UpdateToolbarIcons();
        }

        private async void 加载实时数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501&lonlat=116.407526,39.904030";
                string token = "3a1279f1b3c64f9d8b95e68d2ce3206f";

                // 添加等待提示
                Current = WaitCursor;
                加载实时数据ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                加载实时数据ToolStripMenuItem.Enabled = true;
            }
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            cmbPollutant.Items.AddRange(new string[] { "PM2.5", "PM10", "NO₂", "SO₂", "CO", "O₃" });
            cmbPollutant.SelectedIndex = 0; // 默认显示 PM2.5
        }
        private double GetPollutantValue(AirStation station, string type)
        {
            switch (type.ToUpper())
            {
                case "PM2.5": return station.pm25;
                case "PM10": return station.pm10;
                case "NO₂": return station.no2;
                case "SO₂": return station.so2;
                case "CO": return station.co;
                case "O₃":
                case "O3": return station.o3;
                default: return 0;
            }
        }
        private void DrawStations(List<AirStation> stations)
        {
            string selectedPollutant = cmbPollutant.SelectedItem.ToString(); // 选中的污染物

            IGraphicsContainer graphicsContainer = axMapControl1.ActiveView.GraphicsContainer;
            graphicsContainer.DeleteAllElements();

            foreach (var station in stations)
            {
                double value = GetPollutantValue(station, selectedPollutant);
                IColor color = SymbolHelper.GetColorByPollutant(selectedPollutant, value);
                ISimpleMarkerSymbol symbol = SymbolHelper.CreatePollutionSymbol(8, color);

                IPoint pt = new PointClass { X = station.lon, Y = station.lat };
                IMarkerElement markerElement = new MarkerElementClass();
                markerElement.Symbol = symbol;
                ((IElement)markerElement).Geometry = pt;

                graphicsContainer.AddElement((IElement)markerElement, 0);
            }

            axMapControl1.ActiveView.Refresh();
        }


        //public void LoadStationsToFeatureLayer(List<AirStation> stations)
        //{
        //    // 创建字段集合
        //    IFields fields = new FieldsClass();
        //    IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

        //    // 添加Shape字段（必须）
        //    IField shapeField = new FieldClass();
        //    IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;
        //    shapeFieldEdit.Name_2 = "Shape";
        //    shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

        //    // 设置为点类型
        //    IGeometryDef geometryDef = new GeometryDefClass();
        //    IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
        //    ISpatialReference spatialRef = axMapControl1.SpatialReference;
        //    if (spatialRef == null)
        //    {
        //        ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
        //        spatialRef = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
        //    }


        //    shapeFieldEdit.GeometryDef_2 = geometryDef;
        //    fieldsEdit.AddField(shapeField);

        //    // 添加属性字段
        //    AddTextField(fieldsEdit, "stationId", 20);
        //    AddTextField(fieldsEdit, "name", 50);
        //    AddDoubleField(fieldsEdit, "lon");
        //    AddDoubleField(fieldsEdit, "lat");
        //    AddDoubleField(fieldsEdit, "pm25");
        //    AddDoubleField(fieldsEdit, "pm10");
        //    AddDoubleField(fieldsEdit, "no2");
        //    AddDoubleField(fieldsEdit, "so2");
        //    AddDoubleField(fieldsEdit, "co");
        //    AddDoubleField(fieldsEdit, "o3");
        //    AddIntegerField(fieldsEdit, "aqi");
        //    AddTextField(fieldsEdit, "aqi_level", 20);

        //    //// 创建内存工作空间
        //    //IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();
        //    //IFeatureWorkspace featureWorkspace = ((IFeatureWorkspace)workspaceFactory.OpenFromFile("", 0));
        //    //IFeatureClass featureClass = featureWorkspace.CreateFeatureClass("AirStations", fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
        //    IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();
        //    IName workspaceName = (IName)workspaceFactory.OpenFromFile("in_memory", 0);
        //    IWorkspace workspace = (IWorkspace)workspaceName;
        //    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;




        //    // 创建要素类
        //    IFeatureClass featureClass = featureWorkspace.CreateFeatureClass("AirStations", fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

        //    // 插入数据
        //    foreach (var station in stations)
        //    {
        //        IFeature feature = featureClass.CreateFeature();
        //        IPoint point = new PointClass { X = station.lon, Y = station.lat };
        //        point.SpatialReference = axMapControl1.SpatialReference;
        //        feature.Shape = point;

        //        feature.set_Value(feature.Fields.FindField("stationId"), station.stationId);
        //        feature.set_Value(feature.Fields.FindField("name"), station.name);
        //        feature.set_Value(feature.Fields.FindField("lon"), station.lon);
        //        feature.set_Value(feature.Fields.FindField("lat"), station.lat);
        //        feature.set_Value(feature.Fields.FindField("pm25"), station.pm25);
        //        feature.set_Value(feature.Fields.FindField("pm10"), station.pm10);
        //        feature.set_Value(feature.Fields.FindField("no2"), station.no2);
        //        feature.set_Value(feature.Fields.FindField("so2"), station.so2);
        //        feature.set_Value(feature.Fields.FindField("co"), station.co);
        //        feature.set_Value(feature.Fields.FindField("o3"), station.o3);
        //        feature.set_Value(feature.Fields.FindField("aqi"), station.aqi);
        //        feature.set_Value(feature.Fields.FindField("aqi_level"), station.aqi_level);
        //        feature.Store();
        //    }

        //    // 加载图层到地图
        //    IFeatureLayer featureLayer = new FeatureLayerClass
        //    {
        //        FeatureClass = featureClass,
        //        Name = "污染站点图层"
        //    };

        //    axMapControl1.Map.AddLayer((ILayer)featureLayer);
        //    axMapControl1.ActiveView.Refresh();
        //}

        //// 辅助字段函数
        //private void AddTextField(IFieldsEdit fieldsEdit, string name, int length)
        //{
        //    IField field = new FieldClass();
        //    IFieldEdit fieldEdit = (IFieldEdit)field;
        //    fieldEdit.Name_2 = name;
        //    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
        //    fieldEdit.Length_2 = length;
        //    fieldsEdit.AddField(field);
        //}

        //private void AddDoubleField(IFieldsEdit fieldsEdit, string name)
        //{
        //    IField field = new FieldClass();
        //    IFieldEdit fieldEdit = (IFieldEdit)field;
        //    fieldEdit.Name_2 = name;
        //    fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
        //    fieldsEdit.AddField(field);
        //}

        //private void AddIntegerField(IFieldsEdit fieldsEdit, string name)
        //{
        //    IField field = new FieldClass();
        //    IFieldEdit fieldEdit = (IFieldEdit)field;
        //    fieldEdit.Name_2 = name;
        //    fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
        //    fieldsEdit.AddField(field);
        //}
        public void LoadStationsToFeatureLayer(List<AirStation> stations)
        {
            try
            {
                // 创建字段集合
                IFields fields = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                // 添加 Shape 字段
                IField shapeField = new FieldClass();
                IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;
                shapeFieldEdit.Name_2 = "Shape";
                shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

                // 定义 Geometry
                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

                ISpatialReference spatialRef = axMapControl1.SpatialReference;
                if (spatialRef == null)
                {
                    ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
                    spatialRef = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                }
                geometryDefEdit.SpatialReference_2 = spatialRef;
                shapeFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(shapeField);

                // 添加属性字段
                AddTextField(fieldsEdit, "stationId", 20);
                AddTextField(fieldsEdit, "name", 50);
                AddDoubleField(fieldsEdit, "lon");
                AddDoubleField(fieldsEdit, "lat");
                AddDoubleField(fieldsEdit, "pm25");
                AddDoubleField(fieldsEdit, "pm10");
                AddDoubleField(fieldsEdit, "no2");
                AddDoubleField(fieldsEdit, "so2");
                AddDoubleField(fieldsEdit, "co");
                AddDoubleField(fieldsEdit, "o3");
                AddIntegerField(fieldsEdit, "aqi");
                AddTextField(fieldsEdit, "aqi_level", 20);

                // 正确方式：创建内存工作空间
                IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();
                IWorkspaceName workspaceName = workspaceFactory.Create("", "TempMemWS", null, 0);
                IName name = (IName)workspaceName;
                IWorkspace workspace = (IWorkspace)name.Open();

                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

                // 创建要素类
                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(
                    "AirStations",
                    fields, null, null,
                    esriFeatureType.esriFTSimple,
                    "Shape", "");

                // 插入数据
                foreach (var station in stations)
                {
                    IFeature feature = featureClass.CreateFeature();
                    IPoint point = new PointClass { X = station.lon, Y = station.lat };
                    point.SpatialReference = spatialRef;
                    feature.Shape = point;

                    feature.set_Value(feature.Fields.FindField("stationId"), station.stationId);
                    feature.set_Value(feature.Fields.FindField("name"), station.name);
                    feature.set_Value(feature.Fields.FindField("lon"), station.lon);
                    feature.set_Value(feature.Fields.FindField("lat"), station.lat);
                    feature.set_Value(feature.Fields.FindField("pm25"), station.pm25);
                    feature.set_Value(feature.Fields.FindField("pm10"), station.pm10);
                    feature.set_Value(feature.Fields.FindField("no2"), station.no2);
                    feature.set_Value(feature.Fields.FindField("so2"), station.so2);
                    feature.set_Value(feature.Fields.FindField("co"), station.co);
                    feature.set_Value(feature.Fields.FindField("o3"), station.o3);
                    feature.set_Value(feature.Fields.FindField("aqi"), station.aqi);
                    feature.set_Value(feature.Fields.FindField("aqi_level"), station.aqi_level);
                    feature.Store();
                }

                // 加载到地图中
                IFeatureLayer featureLayer = new FeatureLayerClass
                {
                    FeatureClass = featureClass,
                    Name = "污染站点图层"
                };

                axMapControl1.Map.AddLayer((ILayer)featureLayer);
                axMapControl1.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建图层失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AddTextField(IFieldsEdit fieldsEdit, string name, int length)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.Length_2 = length;
            fieldsEdit.AddField(field);
        }

        private void AddDoubleField(IFieldsEdit fieldsEdit, string name)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldsEdit.AddField(field);
        }

        private void AddIntegerField(IFieldsEdit fieldsEdit, string name)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(field);
        }

        private void cmbPollutant_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private async void 手动更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501&lonlat=116.407526,39.904030";
                string token = "3a1279f1b3c64f9d8b95e68d2ce3206f";

                // 添加等待提示
                Current = WaitCursor;
                手动更新ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                手动更新ToolStripMenuItem.Enabled = true;
            }
        }

        private void 自动更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (isAutoUpdating)
            {
                // 如果正在自动更新，则停止
                StopAutoUpdate();
                自动更新ToolStripMenuItem.Text = "开始自动更新";
            }
            else
            {
                // 如果未在自动更新，则启动
                StartAutoUpdate();
                自动更新ToolStripMenuItem.Text = "停止自动更新";
            }
        }
        private void StartAutoUpdate()
        {
            if (autoUpdateTimer == null)
            {
                autoUpdateTimer = new System.Timers.Timer(30000); // 30秒间隔
                autoUpdateTimer.Elapsed += async (sender, e) => await AutoUpdateDataAsync();
                autoUpdateTimer.AutoReset = true;
            }

            autoUpdateTimer.Start();
            isAutoUpdating = true;

            // 立即执行一次更新
            _ = AutoUpdateDataAsync();
        }

        private void StopAutoUpdate()
        {
            if (autoUpdateTimer != null)
            {
                autoUpdateTimer.Stop();
            }
            isAutoUpdating = false;
        }

        private async Task AutoUpdateDataAsync()
        {
            // 确保在主线程上更新UI
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(async () => await AutoUpdateDataAsync()));
                return;
            }

            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501&lonlat=116.407526,39.904030";
                string token = "3a1279f1b3c64f9d8b95e68d2ce3206f";

                // 添加等待提示
                Current = WaitCursor;
                自动更新ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("自动更新失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                自动更新ToolStripMenuItem.Enabled = true;
            }
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            StopAutoUpdate(); // 确保窗体关闭时停止定时器
        }
    }
}
